import {
  getDepartmentTable,
  editeDepartmentRecord
} from '../../api/department'
import {
  DEPARTMENT_LIST,
  DEPARTMENT_CURRENT_ROW,
  DEPARTMENT_DATA_COUNT,
  DEPARTMENT_HISTORY_DATA,
  DEPARTMENT_UPLOAD_LIST
} from '../motations-type'

export default {
  state: {
    departmentList: [],
    departmentDataCount: null,
    pageSize: 20,
    departmentHistoryData: [],
    row: {
      name: '',
      des: '',
      state: ''
    }
  },
  getters: {
    departmentList: state => state.departmentList
  },
  mutations: {
    [DEPARTMENT_LIST] (state, data) {
      state.departmentList = data
    },
    [DEPARTMENT_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [DEPARTMENT_DATA_COUNT] (state, data) {
      state.departmentDataCount = data
    },
    [DEPARTMENT_HISTORY_DATA] (state, data) {
      state.departmentHistoryData = data
    },
    [DEPARTMENT_UPLOAD_LIST] (state, data) {
      state.departmentList = state.departmentList.push(data)
    }
  },
  actions: {
    async getDepartmentList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      let newTotal = null
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getDepartmentTable(data)
      resp.data.data.map((item) => {
        newData = [...newData, {
          id: item.id,
          name: item.name,
          des: item.des ? item.des : '-',
          state: item.state.toString()
        }]
      })
      commit(DEPARTMENT_LIST, newData)
      commit(DEPARTMENT_DATA_COUNT, newData.length)
      if (newData.length < rootState.department.pageSize) {
        commit(DEPARTMENT_HISTORY_DATA, newData)
      } else {
        commit(DEPARTMENT_HISTORY_DATA, newData.slice(0, rootState.department.pageSize))
      }
    },
    async changeDepartmentPage ({ commit, rootState }, index) {
      let data = rootState.department.departmentList
      let _start = (index - 1) * rootState.department.pageSize
      let _end = index * rootState.department.pageSize
      commit(DEPARTMENT_HISTORY_DATA, data.slice(_start, _end))
    },
    async updateDepartmentData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      await editeDepartmentRecord(data)
    },
    async getDepartmentCurrentRow ({ commit, rootState }, row) {
      commit(DEPARTMENT_CURRENT_ROW, row)
    },
    async getDepartmentUploadList ({ commit, rootState }, uploadList) {
      commit(DEPARTMENT_UPLOAD_LIST, uploadList)
    }
  }
}
